<?php


namespace App\Http\Controllers\Api;

use App\User;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\JWTAuth;


class HhxController extends BaseController
{
    protected $jwt;


    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

    // 获取token
    public function token($array)
    {
        try {
            if (!$token = $this->jwt->attempt($array)) {
                return false;//账户与密码不一致
            } else {
                return $token;//返回token值
            }
        } catch (TokenExpiredException $e) {
            return response()->json(['token_expired'], $e->getStatusCode());
        } catch (TokenInvalidException $e) {
            return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (JWTException $e) {
            return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
        }
    }

    // 用户登录
    function signIn(Request $request)
    {
        $mobile = $request->input('mobile');//账号
        $password = $request->input('password');//密码
        $state = $request->input('state');//协议状态

        if ($state != 1) {
            return $this->fail('未同意用户协议');
        }
        if (empty($mobile) || empty($password)) {
            return $this->fail('填写信息不能为空');

        }
        $token = $this->token(['login_name' => $mobile, 'password' => $password]);//token值（这个是和User模型对应的）
        if ($token == false) {
            return $this->fail('账户与密码不一致');
        }
        $data['token'] = $token;
        return $this->success($data);
    }

    /**
     * 注册
     * @param Request $request
     */
    public function register(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'name' => 'required|string',
            'password' => 'required|string',
            'phone' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }
        $name = $request->get('name');//账号
        $password = $request->get('password');//密码
        $phone = $request->get('phone');//密码
        $user = new User();
        $user->name = $name;
        $user->password = Hash::make($password);
        $user->phone = $phone;
        $user->save();
        $token = $this->token(['phone' => $phone, 'password' => $password]);//token值（这个是和User模型对应的）
        if ($token == false) return $this->response->error('账户与密码不一致.', 302);
        $data['token'] = $token ? $token : '';
        return $this->response->array($data);
    }

    public function getUser()
    {
        return response()->json(Auth::user());
    }


}
